<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>单例模式--闭包</title>
</head>
<body>
    <script>
        //回到函数，闭包
        //自由变量，用来访问唯一的实例
        function StorageBase(){

        }
        StorageBase.prototype.getItem = function(key){
            return localStorage.getItem(key)
        }
        StorageBase.prototype.setItem = function(key,value){
           localStorage.setItem(key,value)
        }
        /* const stroage1 = new StorageBase()
        const stroage2 = new StorageBase()
        console.log(stroage1 === stroage2) //false 两个实例不相等 */

        const Stroage = (function(){
            let instance = null // 闭包 自由变量
            return function(){
                if(!instance){
                    instance = new StorageBase()
                }
                return instance
            }
        })()
        const stroage1 =new Stroage()
        const stroage2 =new Stroage() //为什么这里又能new了？
        console.log(stroage1 === stroage2) //true 两个实例相等
        //为什么相等？ 
        //new 没有产生新的实例，而是返回了instance，instance是一个对象，
        stroage1.setItem('name','张三') 
        console.log(stroage1.getItem('name'))
        console.log(stroage2.getItem('name')) 
        //为什么stroage1和stroage2都能访问到instance？


    </script>
</body>
</html>